package com.kinyx.examples.services.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kinyx.examples.entities.impl.EnumEntity;
import com.kinyx.examples.enums.impl.Gender;
import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;

@Service
public class EnumService {

	private static final Gender GENDER = Gender.MALE;

	@Autowired
	private SessionFactory sessionFactory;

	public void persist() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		final EnumEntity entity = new EnumEntity();
		entity.setE1(GENDER);
		entity.setE2(GENDER);
		entity.setE3(GENDER);
		entity.setCe(GENDER);
		session.persist(entity);
		System.out.println(entity);
		session.getTransaction().commit();
		session.close();
	}

	public void check() {
		final Session session = this.sessionFactory.openSession();
		session.createQuery("from " + EnumEntity.class.getSimpleName(), EnumEntity.class).getResultList().forEach(entity -> {
			System.out.println(entity);
			if (!GENDER.equals(entity.getE1())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
			if (!GENDER.equals(entity.getE2())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
			if (!GENDER.equals(entity.getE3())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
			if (!GENDER.equals(entity.getCe())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
		});
		session.close();
	}

	public void clear() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		session.createQuery("delete from " + EnumEntity.class.getSimpleName()).executeUpdate();
		session.getTransaction().commit();
		session.close();
	}

}
